#include "App.h"

#include "Logging.h"

le::App::App()
	: m_DisplayWindow(NULL)
	, m_DisplayRenderer(NULL)
{

}

le::App::~App()
{

}

bool le::App::Init(le::StartupStruct& startupStruct )
{
	SDL_Init(SDL_INIT_VIDEO);
	SDL_RendererInfo displayRendererInfo;
	m_DisplayWindow = SDL_CreateWindow("LeJeux", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
	// SDL_CreateWindowAndRenderer(800, 600, SDL_WINDOW_OPENGL, &m_DisplayWindow, &m_DisplayRenderer);
	m_DisplayRenderer = SDL_CreateRenderer(m_DisplayWindow, -1, SDL_RendererFlags::SDL_RENDERER_ACCELERATED);
	SDL_GetRendererInfo(m_DisplayRenderer, &displayRendererInfo);
	/*TODO: Check that we have OpenGL */
	if ((displayRendererInfo.flags & SDL_RENDERER_ACCELERATED) == 0 ||  (displayRendererInfo.flags & SDL_RENDERER_TARGETTEXTURE) == 0) 
	{
		/*TODO: Handle this. We have no render surface and not accelerated. */
		LeOutputDebugString("Failed to init SDL!");
		CleanupSDL();
		return false;

	}

	startupStruct.m_Window = m_DisplayWindow;
	return true;
}

void le::App::CleanupSDL()
{
	SDL_Quit();
}

int le::App::Run()
{
	SDL_Event sdlEvent;
	bool quitRequested = false;
	for(;!quitRequested;)
	{
		while (SDL_PollEvent(&sdlEvent))
		{
			switch(sdlEvent.type)
			{
			case SDL_QUIT:
				quitRequested = true;
				break;
			case SDL_KEYDOWN:
			case SDL_KEYUP:
			case SDL_TEXTEDITING: 
			case SDL_TEXTINPUT:   
			case SDL_MOUSEMOTION:
			case SDL_MOUSEBUTTONDOWN: 
			case SDL_MOUSEBUTTONUP:
			case SDL_MOUSEWHEEL:  
				OnInputEvent(sdlEvent);
				break;
			}
		}
		SDL_RenderClear(m_DisplayRenderer);
		SDL_RenderPresent(m_DisplayRenderer);
		Update();
	}

	return 0;
}
